const { foodsModel } = require('../models/foodsModel');
const { classifysModel } = require('../models/classifysModel');

//获取所有菜谱
module.exports.getAllFoods = async function ({ pageSize, currentPage }) {
    const total = await foodsModel.countDocuments();
    const data = await foodsModel.find()
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
        .populate('classifysId');
    return { total, data };
}


//获取菜谱详情

module.exports.getDetails = async function ({ foodsId }) {
    const data = await foodsModel.find({ _id: foodsId }).populate('classifysId');
    console.log(data)
    return data;
}
//搜索菜谱


module.exports.searchFoods = async function ({ pageSize, currentPage, content = '' }) {
    const total = await foodsModel.countDocuments({
        $or: [
            { name: { $regex: content, $options: '$i' } },
            { tips: { $regex: content, $options: '$i' } }
        ]
    })
    const data = await foodsModel.find({
        $or: [
            { name: { $regex: content } },
            { tips: { $regex: content } }
        ]
    })
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
        .populate({ path: 'classifysId' })

        ;
    console.log(data);
    return { total, data };
}
//收藏菜谱

module.exports.addCollection = async function ({ foodsId, usersId, focus }) {
    if (focus - 0) {
        console.log('收藏')
        const data = await foodsModel.updateOne({ _id: foodsId },
            { $addToSet: { collect: usersId } }
        );
        return { data, focus: 1 };
    } else {
        console.log('取消')
        const data = await foodsModel.updateOne({ _id: foodsId },
            { $pull: { collect: usersId } }
        );
        return { data, focus: 0 };
    }

}


//新增浏览记录
module.exports.addBrowse = async function ({ foodsId, usersId }) {
    const data = await foodsModel.updateOne({ _id: foodsId },
        { $addToSet: { views: usersId } }
    );
    return data;
}




